
#include "time.h"
#include "graphics.h"

#undef UNICODE
#include <windows.h>


#include "C_Application.h"

const static float GTickFixedDeltaTime = 0.02f;

//global variables
HWND g_HwndMain = NULL;
C_Application::T_PressedKey gPressedKeys = 0;

int screenWidth = 1200;
int screenHeight = 800;

//----------------------------
//----------------------------


static LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam){

   switch(msg){
   case WM_CLOSE:
      PostQuitMessage(0);
      break;
   case WM_PAINT:
      FillRect(0, 0, screenWidth, screenHeight, 0);
      break;
   case WM_KEYDOWN:
      switch(wParam){
      case VK_LEFT: gPressedKeys |= C_Application::s_KeyLeft; break;
      case VK_UP: gPressedKeys |= C_Application::s_KeyUp; break;
      case VK_RIGHT: gPressedKeys |= C_Application::s_KeyRight; break;
      case VK_DOWN: gPressedKeys |= C_Application::s_KeyDown; break;
      case VK_SPACE: gPressedKeys |= C_Application::s_KeySpace; break;
      case VK_ESCAPE:
         PostQuitMessage(0);
         break;
      }
      break;
   case WM_KEYUP:
      switch(wParam){
			case VK_LEFT: gPressedKeys &= ~C_Application::s_KeyLeft; break;
			case VK_UP: gPressedKeys &= ~C_Application::s_KeyUp; break;
			case VK_RIGHT: gPressedKeys &= ~C_Application::s_KeyRight; break;
			case VK_DOWN: gPressedKeys &= ~C_Application::s_KeyDown; break;
			case VK_SPACE: gPressedKeys &= ~C_Application::s_KeySpace; break;
      }
      break;
   }
   return DefWindowProc(hwnd, msg, wParam, lParam);
}


//----------------------------
//----------------------------


int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow){

	//initialize graphics library
	// *** do not remove ***
	s_init	init;
	memset(&init, 0, sizeof(init));

	init.captionText = "test";
	init.instance = hInstance;
	init.wndProc = WndProc;
	init.screenWidth = screenWidth;
	init.screenHeight = screenHeight;

	g_HwndMain = InitializeGraphics( init );

   //clear screen
   FillRect(0, 0, screenWidth, screenHeight, 0);
  

	{
        C_Application::CreateInstance(screenWidth,screenHeight);
		unsigned int last_time = timeGetTime();

	  //main game loop
		while(true){
			//pause 20 miliseconds
            int fixedTickMilliseconds = GTickFixedDeltaTime * 1000;

			int i = timeGetTime();
			if(i-last_time < fixedTickMilliseconds) Sleep(fixedTickMilliseconds - (i-last_time));
			last_time = i;
			//windows messaging
			// *** do not remove ***
			MSG msg;
			if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)){
				if(msg.message==WM_QUIT) break;
				TranslateMessage(&msg);
				DispatchMessage(&msg);
			}


			C_Application::GetInstance()->Tick(gPressedKeys, GTickFixedDeltaTime);

		}
	}

   //uninitialize graphics
   // *** do not remove ***
   UnitializeGraphics();

   return 0;
}
